package utils;

import java.sql.*;

public class DBUtil {
    //1.定义mysql地址，账号，密码，编码
  static final  String URL="jdbc:mysql:///test?characterEncoding=utf8";
  static final  String USER="root";
  static final  String PSW="root";
    //2.注册驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    //3.获取连接对象方法
    public static Connection getConn() throws SQLException {
        Connection conn = DriverManager.getConnection(URL, USER, PSW);
        return conn;
    }
    //4.通用的查询方法，接收sql,返回结果集
    public static ResultSet query(String sql,Object... keys){
        ResultSet rs = null;
        try {
            //1.获取连接对象
            Connection conn = getConn();
            //2.获取执行sql的对象
            PreparedStatement pst = conn.prepareStatement(sql);
            //3.遍历keys,将数据赋值给？
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i+1),keys[i]);
            }
            //4.pst调用查询方法执行mysql
            rs = pst.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return rs;
    }
    //5.通用的update方法
    public static int update(String sql,Object... keys){
        int num = 0;
        try {
            //1.获取连接对象
            Connection conn = getConn();
            //2.获取执行sql的对象
            PreparedStatement pst = conn.prepareStatement(sql);
            //3.遍历keys,将数据赋值给？
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i+1),keys[i]);
            }
            //4.pst调用查询方法执行mysql
            num = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return num;
    }
}
